package com.zhida.chatservice.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhida.chatservice.entity.GroupMessage;
import com.zhida.chatservice.entity.UserMessage;
import com.zhida.common.entity.AllMessage;
import com.zhida.common.entity.OfflineMessage;
import com.zhida.common.utils.ObjectUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.*;

import static com.zhida.common.utils.RegexUtil.*;

/**
 * Create by zhh 2024/7/17 9:44
 */
public class MsgUtil {

    public static void cachingOfflineMsg(RedisTemplate<String,String> redisTemplate, String message) throws JsonProcessingException {
        JsonNode jsonMsg = ObjectUtil.JsonStr2Object(message);
//        用户是否在线
        String to = redisTemplate.opsForValue().get(WS_USER_KEY + jsonMsg.get("to").asText());
        to = jsonMsg.get("to").asText();
        String from = jsonMsg.get("from").asText();
        String msg = jsonMsg.get("msg").asText();
//            接收消息方
        String originMsg = redisTemplate.opsForValue().get(WS_OFFLINE_KEY + to);
//            获取当前时间戳
        long time = System.currentTimeMillis();
        ObjectMapper mapper = new ObjectMapper();
        if ( originMsg == null) {
            ArrayList<HashMap<String, ArrayList<OfflineMessage>>> msgArr = new ArrayList<>();
            saveCaching(redisTemplate, to, from, msg, time, mapper, msgArr);
        } else {
            ArrayList<HashMap<String, ArrayList<OfflineMessage>>> msgArr = mapper.readValue(originMsg, new TypeReference<ArrayList<HashMap<String, ArrayList<OfflineMessage>>>>() {});
            // 例如，遍历msgArr并打印内容
            for (Map<String, ArrayList<OfflineMessage>> hashMap : msgArr) {
//                    对比hashmap的key和from是否相同
                if (hashMap.containsKey(from)) {
//                        相同
                    hashMap.get(from).add(new OfflineMessage(time,msg));
                    redisTemplate.opsForValue().set(WS_OFFLINE_KEY + to, mapper.writeValueAsString(msgArr));
//                        break;
                    return;
                }
            }
//                如果for中煤找到对应的数据，则新建一个放入msgArr中
            saveCaching(redisTemplate, to, from, msg, time, mapper, msgArr);
        }
    }

    private static void saveCaching(RedisTemplate<String, String> redisTemplate, String to, String from, String msg, long time, ObjectMapper mapper, ArrayList<HashMap<String, ArrayList<OfflineMessage>>> msgArr) throws JsonProcessingException {
        HashMap<String,ArrayList<OfflineMessage>> hashMap = new HashMap<>();
        hashMap.put(from, new ArrayList<>(Arrays.asList(new OfflineMessage(time,msg))));
        msgArr.add(hashMap);
        redisTemplate.opsForValue().set(WS_OFFLINE_KEY + to, mapper.writeValueAsString(msgArr));
    }

    public static void cachingAllMsg(RedisTemplate<String,String> redisTemplate,String message) throws JsonProcessingException {
        JsonNode jsonMsg = ObjectUtil.JsonStr2Object(message);
//        用户是否在线
        String to = redisTemplate.opsForValue().get(WS_USER_KEY + jsonMsg.get("to").asText());
        to = jsonMsg.get("to").asText();
        String from = jsonMsg.get("from").asText();
        String msg = jsonMsg.get("msg").asText();
//            接收消息方
        String originMsg = redisTemplate.opsForValue().get(WS_PERSONAL_MSG_KEY + from + ":" + to);
        if (StringUtils.isBlank(originMsg)){
            originMsg = redisTemplate.opsForValue().get(WS_PERSONAL_MSG_KEY + to + ":" + from);
        }
//            获取当前时间戳
        String time = String.valueOf(System.currentTimeMillis());
        ObjectMapper mapper = new ObjectMapper();
        ArrayList<AllMessage> msgArr = new ArrayList<>();

//        读取源消息
        if (StringUtils.isNotBlank(originMsg)){
            msgArr = mapper.readValue(originMsg,ArrayList.class);
//            新建一条消息并存入
            msgArr.add(new AllMessage(from,time,msg));
        }else {
            msgArr.add(new AllMessage(from,time,msg));
        }
        if (StringUtils.isNotBlank(redisTemplate.opsForValue().get(WS_PERSONAL_MSG_KEY + from + ":" + to))){
            redisTemplate.opsForValue().set(WS_PERSONAL_MSG_KEY + from + ":" + to, mapper.writeValueAsString(msgArr));
        }else {
            redisTemplate.opsForValue().set(WS_PERSONAL_MSG_KEY + to + ":" + from, mapper.writeValueAsString(msgArr));
        }
    }

    public static List<UserMessage> backupUserMessage(RedisTemplate<String,String> redisTemplate, StringRedisTemplate stringRedisTemplate) throws JsonProcessingException {
        List<UserMessage> userMessages = new ArrayList<>();
        Set<String> keys = stringRedisTemplate.keys(WS_PERSONAL_MSG_KEY + "*");
        ObjectMapper mapper = new ObjectMapper();
        for (String key : keys) {
            String[] split = key.split(":");
            String user1 = split[split.length-1];
            String user2 = split[split.length-2];
            String originMsg = redisTemplate.opsForValue().get(key);
//            将key的redis缓存移除
            redisTemplate.delete(key);
            ArrayList<AllMessage> msgArr = mapper.readValue(originMsg, new TypeReference<ArrayList<AllMessage>>() {});
            for (AllMessage allMessage : msgArr) {
//                格式化时间
//                将allMessage.getTime()得到的时间戳转换成对应的LocalDateTime，并创建新的变量LocalTime time
                if (user1.equals(allMessage.getFrom())){
                    userMessages.add(new UserMessage(user2,allMessage.getFrom(),allMessage.getTime(),allMessage.getMsg()));
                }else {
                    userMessages.add(new UserMessage(user1,allMessage.getFrom(),allMessage.getTime(),allMessage.getMsg()));
                }
            }
        }
        return userMessages;
    }

    public static List<GroupMessage> backupGroupMessage(RedisTemplate<String, String> redisTemplate, StringRedisTemplate stringRedisTemplate) throws JsonProcessingException {
        List<GroupMessage> groupMessages = new ArrayList<>();
        Set<String> keys = stringRedisTemplate.keys(WS_GROUP_MSG_KEY + "*");
        ObjectMapper mapper = new ObjectMapper();
        for (String key : keys) {
            String[] split = key.split(":");
            String group_id = split[split.length-1];
            String originMsg = redisTemplate.opsForValue().get(key);
            redisTemplate.delete(key);
            ArrayList<AllMessage> msgArr = mapper.readValue(originMsg, new TypeReference<ArrayList<AllMessage>>() {});
            for (AllMessage allMessage : msgArr){
                groupMessages.add(new GroupMessage(group_id,allMessage.getFrom(),allMessage.getTime(),allMessage.getMsg()));
            }
        }
        return groupMessages;
    }
}
